const express = require('express');
const router = express.Router();

const md5 = require('md5');
const { RES_CODE } = require('../utils/constants');
const verifyToken = require('../middlewares/verifyToken');
const userModel = require('../db/models/UserModel');
const { createToken } = require('../utils/tokenUtils');


// 登录接口
router.post('/login', async (req, res) => {

    // 获取前端发送来的数据
    let { username, pwd } = req.body;

    try {
        // 是否登录成功
        let user = await userModel.findOne({ username, pwd: md5(pwd) })


        if (user) {
            //登录成功才 创建token
            let token = createToken(user._id);
            res.json({
                code: RES_CODE.SUCCESS,
                message: '登录请求成功',
                data: {
                    token,
                    user
                }
            })
        } else {
            // 账号密码错误
            res.json({
                code: RES_CODE.DATA_ERROR,
                message: '登录账号或密码错误'
            })
        }
    }catch(e){
        res.json({
            code:RES_CODE.SERVER_ERROR,
            message:'服务器错误'+e
        })
    }
})

// 获取登录用户信息
router.get('/info',verifyToken,async (req,res)=>{

    // console.log(req.userId)

   try{
    let user = await userModel.findById(req.userId);

    res.json({
        code:RES_CODE.SUCCESS,
        data:user,
        message: "获取用户信息成功"
    })
   }catch(e){
       res.json({
           code:RES_CODE.SERVER_ERROR,
           message:'服务器错误'+e
       })
   }

});

// 退出登录
router.get('/logout',verifyToken,(req,res)=>{
    res.send({
        code:RES_CODE.SUCCESS,
        message:'退出成功'
    });
});

module.exports = router;